package com.yingxin.yxerp.module.dingtalk.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.dingtalk.constant.WeComUrlConstant;
import com.yingxin.yxerp.module.dingtalk.dto.SendWeComWebHootTextDto;
import com.yingxin.yxerp.module.dingtalk.dto.WeComMessageResultDto;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Collections;

/**
 * 调用企业微信WebHoot
 * yuebao
 * 2024-10-23
 */

public class SendWeComWebHootUtil {

    private static HttpHeaders setRestTemplate(){
        HttpHeaders headers = new HttpHeaders();
        org.springframework.http.MediaType mediaType = new org.springframework.http.MediaType(
                "application", "json", Charset.forName("UTF-8") );
        headers.setContentType( mediaType );
        headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON_UTF8 ) );

        return headers;
    }

    /**
     * 发送消息
     */
    public static void sendMessage(SendWeComWebHootTextDto msg, RestTemplate restTemplate){
        String json = JSON.toJSONString( msg );
        sendText( json, restTemplate );
    }

    private static void sendText( String json, RestTemplate restTemplate ){
        try {
            HttpHeaders headers = setRestTemplate();

            HttpEntity<String> request = new HttpEntity<>(json, headers);

            ResponseEntity<String> response = restTemplate.postForEntity(
                    WeComUrlConstant.WEB_HOOK, request, String.class);

            WeComMessageResultDto dto = JSON.parseObject(
                    response.getBody(), new TypeReference<WeComMessageResultDto>(){} );

            if( !dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
                throw new BizException( dto.getErrmsg() );
            }
        } catch (Exception e){
            throw new BizException( e.getMessage() );
        }
    }

}
